<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sentinel | Hexo</title>
  <meta name="keywords" content=" Spring Cloud Alibaba ">
  <meta name="description" content="Sentinel | Hexo">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="如何解决消息过期失效问题RabbtiMQ 是可以设置过期时间的，也就是 TTL。如果消息在 queue 中积压超过一定的时间就会被 RabbitMQ 给清理掉，这个数据就没了。这就是说数据不会大量积压在 mq 里，而是大量的数据会直接搞丢。解决方法就是采用批量重导。 批量重导，也就是后期的一种手动补偿手段。当高峰期过去之后将丢失的那部分数据，写个临时程序查出来，重新放到MQ里，把白天的数据补回来。">
<meta property="og:type" content="article">
<meta property="og:title" content="Rabbit MQ（面试）">
<meta property="og:url" content="https://xiaomaer-sss.gitee.io/xiaomaer-sss/2023/02/03/Rabbit%20MQ%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="如何解决消息过期失效问题RabbtiMQ 是可以设置过期时间的，也就是 TTL。如果消息在 queue 中积压超过一定的时间就会被 RabbitMQ 给清理掉，这个数据就没了。这就是说数据不会大量积压在 mq 里，而是大量的数据会直接搞丢。解决方法就是采用批量重导。 批量重导，也就是后期的一种手动补偿手段。当高峰期过去之后将丢失的那部分数据，写个临时程序查出来，重新放到MQ里，把白天的数据补回来。">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2023-02-03T13:04:21.063Z">
<meta property="article:modified_time" content="2023-02-04T03:42:41.460Z">
<meta property="article:author" content="kiwi">
<meta property="article:tag" content="队列">
<meta property="article:tag" content="异步">
<meta name="twitter:card" content="summary">


<link rel="icon" href="/img/avatar.jpg">

<link href="/css/style.css?v=1.1.0" rel="stylesheet">

<link href="/css/hl_theme/atom-light.css?v=1.1.0" rel="stylesheet">

<link href="//cdn.jsdelivr.net/npm/animate.css@4.1.0/animate.min.css" rel="stylesheet">

<script src="//cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="/js/titleTip.js?v=1.1.0" ></script>

<script src="//cdn.jsdelivr.net/npm/highlightjs@9.16.2/highlight.pack.min.js"></script>
<script>
    hljs.initHighlightingOnLoad();
</script>

<script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js"></script>



<script src="//cdn.jsdelivr.net/npm/jquery.cookie@1.4.1/jquery.cookie.min.js" ></script>

<script src="/js/iconfont.js?v=1.1.0" ></script>

<meta name="generator" content="Hexo 5.4.2"></head>
<div style="display: none">
  <input class="theme_disqus_on" value="false">
  <input class="theme_preload_comment" value="">
  <input class="theme_blog_path" value="">
  <input id="theme_shortcut" value="true" />
  <input id="theme_highlight_on" value="true" />
  <input id="theme_code_copy" value="true" />
</div>



<body>
<aside class="nav">
    <div class="nav-left">
        <a href="/"
   class="avatar_target">
    <img class="avatar"
         src="/img/avatar.jpg"/>
</a>
<div class="author">
    <span>kiwi</span>
</div>

<div class="icon">
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
            <a title="csdn"
               href="https://blog.csdn.net/weixin_45340300?type=blog"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-csdn"></use>
                    </svg>
                
            </a>
        
    
        
    
        
    
        
            <a title="email"
               href="mailto:jackma.h@foxmail.com"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-email"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="qq"
               href="http://wpa.qq.com/msgrd?v=3&uin=761791958&site=qq&menu=yes"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-qq"></use>
                    </svg>
                
            </a>
        
    
        
    
        
    
</div>




<ul>
    <li>
        <div class="all active" data-rel="All">All
            
                <small>(34)</small>
            
        </div>
    </li>
    
        
            
                <li>
                    <div data-rel="开发">
                        <i class="fold iconfont icon-right"></i>
                        
                        开发
                        <small>(34)</small>
                        
                    </div>
                    
                        <ul class="sub hide">
                            
                                <li>
                                    <div data-rel="开发<--->框架">
                                        
                                        框架
                                        
                                            <small>(14
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                                <li>
                                    <div data-rel="开发<--->其他">
                                        
                                        其他
                                        
                                            <small>(5
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                                <li>
                                    <div data-rel="开发<--->数据库">
                                        
                                        数据库
                                        
                                            <small>(2
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                                <li>
                                    <div data-rel="开发<--->疑难杂症">
                                        
                                        疑难杂症
                                        
                                            <small>(2
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                                <li>
                                    <div data-rel="开发<--->中间件">
                                        
                                        中间件
                                        
                                            <small>(5
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                                <li>
                                    <div data-rel="开发<--->Java">
                                        
                                        Java
                                        
                                            <small>(6
                                                )</small>
                                        
                                    </div>
                                    
                                </li>
                            
                        </ul>
                    
                </li>
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
</ul>
<div class="left-bottom">
    <div class="menus">
        
            
            
            
    </div>
    <div>
        
        
    </div>
</div>
<input type="hidden" id="yelog_site_posts_number" value="34">
<input type="hidden" id="yelog_site_word_count" value="83.6k">
<div style="display: none">
    <span id="busuanzi_value_site_uv"></span>
    <span id="busuanzi_value_site_pv"></span>
</div>

    </div>
    <div class="nav-right">
        <div class="friends-area">
    <div class="friends-title">
        Links
        <i class="iconfont icon-left"></i>
    </div>
    <div class="friends-content">
        <ul>
            
            <li><a target="_blank" href="https://xiaomaer-sss.gitee.io/">叶落阁</a></li>
            
        </ul>
    </div>
</div>
        <div class="title-list">
    <div class="right-top">
        <div id="default-panel">
            <i class="iconfont icon-search" data-title="搜索 快捷键 i"></i>
            <div class="right-title">All</div>
            <i class="iconfont icon-file-tree" data-title="切换到大纲视图 快捷键 w"></i>
        </div>
        <div id="search-panel">
            <i class="iconfont icon-left" data-title="返回"></i>
            <input id="local-search-input" autocomplete="off"/>
            <label class="border-line" for="input"></label>
            <i class="iconfont icon-case-sensitive" data-title="大小写敏感"></i>
            <i class="iconfont icon-tag" data-title="标签"></i>
        </div>
        <div id="outline-panel" style="display: none">
            <div class="right-title">大纲</div>
            <i class="iconfont icon-list" data-title="切换到文章列表"></i>
        </div>
    </div>

    <div class="tags-list">
    <input id="tag-search" />
    <div class="tag-wrapper">
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>队列</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>分布式</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>缓存</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>流式处理</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>区块链</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>实战面试题</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>数据库</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>异步</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Bug</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Docker</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Java</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Java-集合</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Java-进阶</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Java-JVM</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Java基础</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>LB</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>MQ</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Mybatis</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>MySQL</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Redis</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Spring</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>Spring Cloud Alibaba</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>SpringBoot</a>
            </li>
        
    </div>

</div>

    
    <nav id="title-list-nav">
        
        
        <a  class="All 开发 中间件 "
           href="/xiaomaer-sss/2023/02/03/Rabbit%20MQ%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="队列,异步"
           data-author="" >
            <span class="post-title" title="Rabbit MQ（面试）">Rabbit MQ（面试）</span>
            <span class="post-date" title="2023-02-03 21:04:21">2023/02/03</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/02/03/%E5%AE%9E%E6%88%98%E9%9D%A2%E8%AF%95%E9%A2%98%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="实战面试题"
           data-author="" >
            <span class="post-title" title="实战面试题">实战面试题</span>
            <span class="post-date" title="2023-02-03 17:11:07">2023/02/03</span>
        </a>
        
        
        <a  class="All 开发 中间件 "
           href="/xiaomaer-sss/2023/02/02/Kafka%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="分布式,流式处理,MQ"
           data-author="" >
            <span class="post-title" title="Kafka（面试）">Kafka（面试）</span>
            <span class="post-date" title="2023-02-02 09:51:06">2023/02/02</span>
        </a>
        
        
        <a  class="All 开发 中间件 "
           href="/xiaomaer-sss/2023/02/02/Zookeeper%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="分布式"
           data-author="" >
            <span class="post-title" title="Zookeeper（面试）">Zookeeper（面试）</span>
            <span class="post-date" title="2023-02-02 09:50:33">2023/02/02</span>
        </a>
        
        
        <a  class="All 开发 中间件 "
           href="/xiaomaer-sss/2023/02/01/Redis%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Redis,缓存"
           data-author="" >
            <span class="post-title" title="Redis（面试）">Redis（面试）</span>
            <span class="post-date" title="2023-02-01 14:09:09">2023/02/01</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/30/SpringBoot%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="SpringBoot"
           data-author="" >
            <span class="post-title" title="SpringBoot（面试）">SpringBoot（面试）</span>
            <span class="post-date" title="2023-01-30 20:26:42">2023/01/30</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/30/Mybatis%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Mybatis"
           data-author="" >
            <span class="post-title" title="Mybatis（面试）">Mybatis（面试）</span>
            <span class="post-date" title="2023-01-30 19:13:44">2023/01/30</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/30/Spring%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Spring"
           data-author="" >
            <span class="post-title" title="Spring（面试）">Spring（面试）</span>
            <span class="post-date" title="2023-01-30 19:12:30">2023/01/30</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/01/29/Java-JVM%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Java-JVM"
           data-author="" >
            <span class="post-title" title="Java-JVM（面试）">Java-JVM（面试）</span>
            <span class="post-date" title="2023-01-29 16:31:34">2023/01/29</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/01/29/Java-%E8%BF%9B%E9%98%B6%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Java-进阶"
           data-author="" >
            <span class="post-title" title="Java-进阶（面试）">Java-进阶（面试）</span>
            <span class="post-date" title="2023-01-29 13:11:10">2023/01/29</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/01/29/Java-%E9%9B%86%E5%90%88%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Java-集合"
           data-author="" >
            <span class="post-title" title="Java-集合（面试）">Java-集合（面试）</span>
            <span class="post-date" title="2023-01-29 09:18:51">2023/01/29</span>
        </a>
        
        
        <a  class="All 开发 数据库 "
           href="/xiaomaer-sss/2023/01/28/%E6%95%B0%E6%8D%AE%E5%BA%93-MySQL%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="MySQL"
           data-author="" >
            <span class="post-title" title="数据库-MySQL（面试）">数据库-MySQL（面试）</span>
            <span class="post-date" title="2023-01-28 16:50:59">2023/01/28</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/01/27/Java-%E5%9F%BA%E7%A1%80%EF%BC%88%E9%9D%A2%E8%AF%95%EF%BC%89/"
           data-tag="Java基础"
           data-author="" >
            <span class="post-title" title="Java-基础（面试）">Java-基础（面试）</span>
            <span class="post-date" title="2023-01-27 19:42:58">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 其他 "
           href="/xiaomaer-sss/2023/01/27/%E5%8C%BA%E5%9D%97%E9%93%BE%E9%92%B1%E5%8C%85/"
           data-tag="区块链"
           data-author="" >
            <span class="post-title" title="区块链钱包">区块链钱包</span>
            <span class="post-date" title="2023-01-27 18:57:51">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 其他 "
           href="/xiaomaer-sss/2023/01/27/Truffle%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/"
           data-tag="区块链"
           data-author="" >
            <span class="post-title" title="Truffle常用命令&amp;Web3常用方法">Truffle常用命令&amp;Web3常用方法</span>
            <span class="post-date" title="2023-01-27 18:57:51">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 其他 "
           href="/xiaomaer-sss/2023/01/27/Truffle&OpenZeppelin%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/"
           data-tag="区块链"
           data-author="" >
            <span class="post-title" title="Truffle&amp;OpenZeppelin环境搭建">Truffle&amp;OpenZeppelin环境搭建</span>
            <span class="post-date" title="2023-01-27 18:57:51">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 其他 "
           href="/xiaomaer-sss/2023/01/27/Solidity/"
           data-tag="区块链"
           data-author="" >
            <span class="post-title" title="Solidity">Solidity</span>
            <span class="post-date" title="2023-01-27 18:57:51">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 中间件 "
           href="/xiaomaer-sss/2023/01/27/Nginx/"
           data-tag="LB"
           data-author="" >
            <span class="post-title" title="Nginx">Nginx</span>
            <span class="post-date" title="2023-01-27 18:57:51">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/27/DockerFile/"
           data-tag="Docker"
           data-author="" >
            <span class="post-title" title="Dockerfile">Dockerfile</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 其他 "
           href="/xiaomaer-sss/2023/01/27/%E5%8C%BA%E5%9D%97%E9%93%BE%E4%B9%8B%E4%BB%A5%E5%A4%AA%E5%9D%8A/"
           data-tag="区块链"
           data-author="" >
            <span class="post-title" title="区块链之以太坊">区块链之以太坊</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 数据库 "
           href="/xiaomaer-sss/2023/01/27/%E5%B8%B8%E7%94%A8SQL%E8%AF%AD%E6%B3%95%E6%95%B4%E7%90%86/"
           data-tag="MySQL,数据库"
           data-author="" >
            <span class="post-title" title="常用SQL语法整理">常用SQL语法整理</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/27/docker%E8%BF%9B%E9%98%B6/"
           data-tag="Docker"
           data-author="" >
            <span class="post-title" title="Docker进阶">Docker进阶</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/27/Docker%E5%9F%BA%E7%A1%80/"
           data-tag="Docker"
           data-author="" >
            <span class="post-title" title="Docker基础">Docker基础</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/27/Docker%E5%AE%89%E8%A3%85%E5%B8%B8%E8%A7%81%E7%BB%84%E4%BB%B6/"
           data-tag="Docker"
           data-author="" >
            <span class="post-title" title="Docker安装常见组件">Docker安装常见组件</span>
            <span class="post-date" title="2023-01-27 17:45:23">2023/01/27</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/SkyWalking/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="SkyWalking">SkyWalking</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/Sentinel/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="Sentinel">Sentinel</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/Seata/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="Seata">Seata</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/Ribbon/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="Ribbon">Ribbon</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 疑难杂症 "
           href="/xiaomaer-sss/2023/01/26/github%E6%8B%89%E5%8F%96%E4%BB%A3%E7%A0%81%E6%8A%A5%20git@github.com's%20password/"
           data-tag="Bug"
           data-author="" >
            <span class="post-title" title="github拉取代码报 &#34;git@github.com&#39;s password&#34;">github拉取代码报 &#34;git@github.com&#39;s password&#34;</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 疑难杂症 "
           href="/xiaomaer-sss/2023/01/26/gitee%E6%90%AD%E5%BB%BA%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%95%99%E7%A8%8B/"
           data-tag="Bug"
           data-author="" >
            <span class="post-title" title="gitee搭建个人博客教程">gitee搭建个人博客教程</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/GateWay/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="GateWay">GateWay</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/26/Fegin/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="Fegin">Fegin</span>
            <span class="post-date" title="2023-01-26 21:39:44">2023/01/26</span>
        </a>
        
        
        <a  class="All 开发 框架 "
           href="/xiaomaer-sss/2023/01/20/Nacos/"
           data-tag="Spring Cloud Alibaba"
           data-author="" >
            <span class="post-title" title="Nacos">Nacos</span>
            <span class="post-date" title="2023-01-20 17:12:00">2023/01/20</span>
        </a>
        
        
        <a  class="All 开发 Java "
           href="/xiaomaer-sss/2023/01/17/hello-world/"
           data-tag="Java"
           data-author="" >
            <span class="post-title" title="Hello World">Hello World</span>
            <span class="post-date" title="2023-01-17 15:40:39">2023/01/17</span>
        </a>
        
        <div id="no-item-tips">

        </div>
    </nav>
    <div id="outline-list">
    </div>
</div>

    </div>
    <div class="hide-list">
        <div class="semicircle" data-title="切换全屏 快捷键 s">
            <div class="brackets first"><</div>
            <div class="brackets">&gt;</div>
        </div>
    </div>
</aside>
<div id="post">
    <div class="pjax">
        <article id="post-Sentinel" class="article article-type-post" itemscope itemprop="blogPost">
    
        <h1 class="article-title">Sentinel</h1>
    
    <div class="article-meta">
        
        
        
        <span class="book">
            <i class="iconfont icon-category"></i>
            
            
            <a  data-rel="开发">开发</a> > 
            
            <a  data-rel="开发&lt;---&gt;框架">框架</a>
            
        </span>
        
        
        <span class="tag">
            <i class="iconfont icon-tag"></i>
            
            <a class="color1">Spring Cloud Alibaba</a>
            
        </span>
        
    </div>
    <div class="article-meta">
        
            Created At : <time class="date" title='Updated At: 2023-01-26 22:07:46'>2023-01-26 21:39</time>
        
    </div>
    <div class="article-meta">
        
        <span>Count:4.6k</span>
        
        
        <span id="busuanzi_container_page_pv">
            Views 👀 :<span id="busuanzi_value_page_pv">
                <span class="count-comment">
                    <span class="spinner">
                      <div class="cube1"></div>
                      <div class="cube2"></div>
                    </span>
                </span>
            </span>
        </span>
        
        
    </div>
    
    <div class="toc-ref">
    
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Sentinel%E5%88%9D%E4%BD%93%E9%AA%8C%EF%BC%88%E6%BA%90%E7%94%9F%E6%96%B9%E5%BC%8F%EF%BC%89"><span class="toc-text">Sentinel初体验（源生方式）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="toc-text">导入依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E6%8E%A7%E4%BD%93%E9%AA%8C%EF%BC%88%E4%BB%A3%E7%A0%81%E7%9A%84%E6%96%B9%E5%BC%8F-%E5%BE%88%E5%B0%91%E4%BD%BF%E7%94%A8%EF%BC%89"><span class="toc-text">流控体验（代码的方式,很少使用）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E6%8E%A7%E4%BD%93%E9%AA%8C%EF%BC%88%E6%B3%A8%E8%A7%A3%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%89"><span class="toc-text">流控体验（注解的方式）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%99%8D%E7%BA%A7%E4%BD%93%E9%AA%8C%EF%BC%88%E6%B3%A8%E8%A7%A3%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%89"><span class="toc-text">降级体验（注解的方式）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Sentinel%E6%8E%A7%E5%88%B6%E5%8F%B0%EF%BC%88%E6%BA%90%E7%94%9F%E6%96%B9%E5%BC%8F%EF%BC%89"><span class="toc-text">Sentinel控制台（源生方式）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8Csentinel%E6%8E%A7%E5%88%B6%E5%8F%B0"><span class="toc-text">运行sentinel控制台</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%99%BB%E5%BD%95sentinel%E6%8E%A7%E5%88%B6%E5%8F%B0"><span class="toc-text">登录sentinel控制台</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9B%86%E6%88%90sentinel%E6%8E%A7%E5%88%B6%E5%8F%B0"><span class="toc-text">集成sentinel控制台</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-Cloud-Alibaba%E6%95%B4%E5%90%88sentinel"><span class="toc-text">Spring Cloud Alibaba整合sentinel</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E5%8F%B0%E8%A7%84%E5%88%99"><span class="toc-text">控制台规则</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#BlockException%E5%BC%82%E5%B8%B8%E7%BB%9F%E4%B8%80%E5%A4%84%E7%90%86"><span class="toc-text">BlockException异常统一处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E6%8E%A7%E8%A7%84%E5%88%99%EF%BC%88flow-contorl%EF%BC%89"><span class="toc-text">流控规则（flow contorl）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%99%90%E6%B5%81%E9%98%88%E5%80%BC%E7%B1%BB%E5%9E%8B"><span class="toc-text">限流阈值类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%81%E6%8E%A7%E6%A8%A1%E5%BC%8F"><span class="toc-text">流控模式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%81%E6%8E%A7%E6%95%88%E6%9E%9C"><span class="toc-text">流控效果</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7"><span class="toc-text">熔断降级</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%86%94%E6%96%AD%E7%AD%96%E7%95%A5"><span class="toc-text">熔断策略</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%83%AD%E7%82%B9%E8%A7%84%E5%88%99"><span class="toc-text">热点规则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B3%BB%E7%BB%9F%E8%A7%84%E5%88%99"><span class="toc-text">系统规则</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#OpenFeign%E6%95%B4%E5%90%88Sentinel"><span class="toc-text">OpenFeign整合Sentinel</span></a></li></ol>
    
<style>
    .left-col .switch-btn,
    .left-col .switch-area {
        display: none;
    }
    .toc-level-3 i,
    .toc-level-3 ol {
        display: none !important;
    }
</style>
</div>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>sentinel分布式系统的流量防卫兵，是阿里巴巴开源的，面向分布式服务架构的高可用防护组件。<br>主要以流量为切入点，从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。 </p>
<p>源码地址： <a target="_blank" rel="noopener" href="https://github.com/alibaba/Sentinel">https://github.com/alibaba/Sentinel</a>  </p>
<p>官方文档： <a target="_blank" rel="noopener" href="https://github.com/alibaba/Sentinel/wiki">https://github.com/alibaba/Sentinel/wiki</a></p>
<p><strong>Sentinel具有以下特征:</strong> </p>
<ul>
<li><strong>丰富的应用场景：</strong>Sentinel承接了阿里巴巴近 10 年的双十一大促流量的核心场景，例如秒杀（即突发流量控 制在系统容量可以承受的范围）、消息削峰填谷、实时熔断下游不可用应用等。 </li>
<li><strong>完备的实时监控：</strong> Sentinel同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据， 甚至 500 台以下规模的集群的汇总运行情况。 </li>
<li><strong>广泛的开源生态：</strong> Sentinel提供开箱即用的与其它开源框架/库的整合模块，例如与 Spring Cloud、Dubbo、 gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入Sentinel。 </li>
<li><strong>完善的 SPI 扩展点：</strong> Sentinel提供简单易用、完善的 SPI 扩展点。您可以通过实现扩展点，快速的定制逻辑。 例如定制规则管理、适配数据源等。 </li>
</ul>
<h2 id="Sentinel初体验（源生方式）"><a href="#Sentinel初体验（源生方式）" class="headerlink" title="Sentinel初体验（源生方式）"></a>Sentinel初体验（源生方式）</h2><p> Sentinel 可以简单的分为 Sentinel 核心库和 Dashboard。核心库不依赖 Dashboard，但是结合 Dashboard 可以取得最好的效果。 </p>
<p>此部分主要介绍 Sentinel 核心库的使用。如果希望有一个最快最直接的了解。</p>
<p>我们说的资源，可以是任何东西，服务，服务里的方法，甚至是一段代码。使用 Sentinel 来进行资源保护，主要分为几个步骤:</p>
<ol>
<li>定义资源</li>
<li>定义规则</li>
<li>检验规则是否生效</li>
</ol>
<p>先把可能需要保护的资源定义好（埋点），之后再配置规则。也可以理解为，只要有了资源，我们就可以在任何时候灵活地定义各种流量控制规则。在编码的时候，只需要考虑这个代码是否需要保护，如果需要保护，就将之定义为一个资源。</p>
<p>对于主流的框架，我们提供适配，只需要按照适配中的说明配置，Sentinel 就会默认定义提供的服务，方法等为资源。</p>
<h3 id="导入依赖"><a href="#导入依赖" class="headerlink" title="导入依赖"></a>导入依赖</h3><pre><code class="pom">&lt;dependencies&gt;
    &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;!--sentinel核心库--&gt;
    &lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.csp&lt;/groupId&gt;
    &lt;artifactId&gt;sentinel-core&lt;/artifactId&gt;
    &lt;version&gt;1.8.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
    &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
    &lt;artifactId&gt;lombok&lt;/artifactId&gt;
    &lt;version&gt;1.18.24&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!--如果需要使用@SentinelResource--&gt;
    &lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.csp&lt;/groupId&gt;
    &lt;artifactId&gt;sentinel-annotation-aspectj&lt;/artifactId&gt;
    &lt;version&gt;1.8.0&lt;/version&gt;
    &lt;/dependency&gt;

&lt;/dependencies&gt;
</code></pre>
<h3 id="流控体验（代码的方式-很少使用）"><a href="#流控体验（代码的方式-很少使用）" class="headerlink" title="流控体验（代码的方式,很少使用）"></a>流控体验（代码的方式,很少使用）</h3><pre><code class="java">@RestController
@Slf4j
public class HelloController &#123;

    private static final String RESOURCE_NAME = &quot;hello&quot;;
    private static final String USER_RESOURCE_NAME = &quot;user&quot;;
    private static final String DEGRADE_RESOURCE_NAME = &quot;degrade&quot;;

    // 进行sentinel流控
    @RequestMapping(&quot;/hello&quot;)
    public String hello()&#123;
        Entry entry = null;
        try &#123;
            // sentinel针对资源进行限制
            entry = SphU.entry(RESOURCE_NAME);
            String str = &quot;hello sentinel&quot;;
            log.info(&quot;+++++++++&quot; + str + &quot;+++++++++&quot;);
            return str;
        &#125; catch (BlockException be)&#123;
            //资源访问阻止，被限流或被降级
            //进行相应的处理操作
            log.info(&quot;block!&quot;);
            return &quot;被流控了&quot;;
        &#125; catch (Exception e) &#123;
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(e, entry);
        &#125;finally &#123;
            if(entry != null)&#123;
                entry.exit();
            &#125;
        &#125;
        return null;
    &#125;


    /**
     * 流控规则
     */
    @PostConstruct
    private static void initFlowRules()&#123;
        // 流控规则
        List&lt;FlowRule&gt; rules = new ArrayList&lt;&gt;();
        // 流控
        FlowRule rule = new FlowRule();
        // 设置被保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则的模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);
        rules.add(rule);

        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    &#125;

&#125;
</code></pre>
<h3 id="流控体验（注解的方式）"><a href="#流控体验（注解的方式）" class="headerlink" title="流控体验（注解的方式）"></a>流控体验（注解的方式）</h3><pre><code class="java">@RestController
@Slf4j
public class HelloController &#123;

    private static final String RESOURCE_NAME = &quot;hello&quot;;
    private static final String USER_RESOURCE_NAME = &quot;user&quot;;
    private static final String DEGRADE_RESOURCE_NAME = &quot;degrade&quot;;

    /**
     * @ SentinelResource 改善接口中资源定义和被流控降级后的处理方法
     *
     * 使用步骤：①添加依赖 sentinel-annotation-aspectj
     *         ②配置bean SentinelResourceAspect
     *用法：
     *  value : 定义资源
     *  blockHandler : 设置流控降级后的处理方法
     *              （默认该方法必须声明在同一个类中，如果不在一个类中可以通过blockHandlerClassZ指定，但方法就需要是static修饰）
     *  fallback : 当接口出现了异常，可以交给fallback指定的方法来处理
     *  blockHandler的优先级高于fallback
     * @param id
     * @return
     */
    @RequestMapping(&quot;/user&quot;)
    @SentinelResource(value = USER_RESOURCE_NAME,fallback = &quot;fallbackForGetUser&quot;, blockHandler = &quot;blockHandlerForGetUser&quot;)
    public User getUser(String id)&#123;
//        int i = 1/0;
        return new User(&quot;kiwi&quot;);
    &#125;


    /**
     *
     * 注意：①一定要是public
     *      ②返回值一定要和源方法保存一致，包含源方法的参数
     *      ③参数的最后添加一个BlockException,可以区分是什么类型的规则处理方法
     *
     * @param id
     * @param be
     * @return
     */
    public User blockHandlerForGetUser(String id, BlockException be)&#123;
        be.printStackTrace();
        return new User(&quot;流控！&quot;);
    &#125;

    public User fallbackForGetUser(String id, Throwable e)&#123;
        e.printStackTrace();
        return new User(&quot;异常了&quot;);
    &#125;

    /**
     * 流控规则
     */
    @PostConstruct
    private static void initFlowRules()&#123;
        // 流控规则
        List&lt;FlowRule&gt; rules = new ArrayList&lt;&gt;();
        // 流控
        FlowRule rule = new FlowRule();
        // 设置被保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则的模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);
        rules.add(rule);

        // 流控
        FlowRule rule2 = new FlowRule();
        // 设置被保护的资源
        rule2.setResource(USER_RESOURCE_NAME);
        // 设置流控规则的模式
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule2.setCount(1);
        rules.add(rule2);

        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    &#125;

&#125;
</code></pre>
<h3 id="降级体验（注解的方式）"><a href="#降级体验（注解的方式）" class="headerlink" title="降级体验（注解的方式）"></a>降级体验（注解的方式）</h3><pre><code class="java">@RestController
@Slf4j
public class HelloController &#123;

    private static final String RESOURCE_NAME = &quot;hello&quot;;
    private static final String USER_RESOURCE_NAME = &quot;user&quot;;
    private static final String DEGRADE_RESOURCE_NAME = &quot;degrade&quot;;

    @RequestMapping(&quot;/degrade&quot;)
    @SentinelResource(value = DEGRADE_RESOURCE_NAME, blockHandler = &quot;blockHandlerForDegrade&quot;)
    public User degrade(String id)&#123;
        throw new RuntimeException(&quot;手动异常&quot;);
    &#125;

    public User blockHandlerForDegrade(String id, BlockException blockException)&#123;
        return new User(&quot;降级了&quot;);
    &#125;

    /**
     * 降级规则
     */
    @PostConstruct
    private static void initDegradeRule()&#123;
        ArrayList&lt;DegradeRule&gt; degradeRules = new ArrayList&lt;&gt;();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        // 设置规则策略：异常数
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);

        // 下面四个参数的意思是：一分钟内，执行了2次出现2次异常就会触发熔断
        // 异常数：2
        degradeRule.setCount(2);
        // 统计时长
        degradeRule.setStatIntervalMs(60*1000);
        // 触发熔断最小请求数：2
        degradeRule.setMinRequestAmount(2);
        // 熔断时长：单位是s
        // 一旦触发了熔断，再次请求对应的接口就会直接调用降级的方法
        // 超过了时间窗口之后就进入半开状态(HALF-OPEN状态)，此代码为10秒。
        //  半开状态：恢复接口请求调用，恢复后如果第一次请求就异常，则再次熔断
        degradeRule.setTimeWindow(10);


        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    &#125;

&#125;
</code></pre>
<h2 id="Sentinel控制台（源生方式）"><a href="#Sentinel控制台（源生方式）" class="headerlink" title="Sentinel控制台（源生方式）"></a>Sentinel控制台（源生方式）</h2><p>sentinel控制台下载地址：<a target="_blank" rel="noopener" href="https://github.com/alibaba/Sentinel/releases">https://github.com/alibaba/Sentinel/releases</a></p>
<p>根据自己的spring cloud版本选择对应的sentinel dashboard版本，我这边采用1.8.0</p>
<h3 id="运行sentinel控制台"><a href="#运行sentinel控制台" class="headerlink" title="运行sentinel控制台"></a>运行sentinel控制台</h3><pre><code class="bash"># 在jar路径下执行 默认是8080端口
java -jar sentinel-dashboard-1.8.0.jar

# 修改端口，用户名密码
java ‐Dserver.port=8858 ‐Dsentinel.dashboard.auth.username=kiwi ‐Dsentinel.dashboard.auth.password=kiwi ‐jar D:\develop\sentinel\sentinel‐dashboard‐1.8.0.jar

# 使用批处理文件的方式
# 1. 桌面创建sentinel_dashborad.bat
# 2. 文件中添加下面的命令
java -Dserver.port=8080 -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=sentinel -jar D:\develop\sentinel\sentinel-dashboard-1.8.0.jar
pause
</code></pre>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671678666986.png" alt="1671678666986"></p>
<h3 id="登录sentinel控制台"><a href="#登录sentinel控制台" class="headerlink" title="登录sentinel控制台"></a>登录sentinel控制台</h3><p>访问地址：<a target="_blank" rel="noopener" href="http://192.168.2.6:8080/">http://192.168.2.6:8080</a></p>
<p>默认账号：sentinel</p>
<p>默认密码：sentinel</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671678719253.png" alt="1671678719253"></p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671678805937.png" alt="1671678805937"></p>
<h3 id="集成sentinel控制台"><a href="#集成sentinel控制台" class="headerlink" title="集成sentinel控制台"></a>集成sentinel控制台</h3><p> 控制台启动后，客户端需要按照以下步骤接入到控制台。 </p>
<ol>
<li><p>添加依赖</p>
<pre><code class="pom">&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.csp&lt;/groupId&gt;
    &lt;artifactId&gt;sentinel-transport-simple-http&lt;/artifactId&gt;
    &lt;version&gt;1.8.0&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li><p>设置JVM参数，并启动项目</p>
<pre><code class="bash"># 在IDEA中设置VM options参数
-Dcsp.sentinel.dashboard.server=127.0.0.1:8080
</code></pre>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671679975092.png" alt="1671679975092"></p>
</li>
<li><p>访问项目中随意一个接口，服务就注册到sentinel控制台中</p>
</li>
</ol>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671680686461.png" alt="1671680686461"></p>
<h2 id="Spring-Cloud-Alibaba整合sentinel"><a href="#Spring-Cloud-Alibaba整合sentinel" class="headerlink" title="Spring Cloud Alibaba整合sentinel"></a>Spring Cloud Alibaba整合sentinel</h2><ol>
<li><p>导入依赖</p>
<pre><code class="pom">&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-alibaba-sentinel&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li><p>添加配置</p>
</li>
</ol>
<pre><code class="yml">server:
  port: 8010

  # 应用名称 （nacos会将该名称当做服务名称）
spring:
  application:
    name: order-service
  cloud:
    nacos:
      server-addr: 192.168.2.6:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public
    sentinel:
      transport:
        dashboard: 127.0.0.1:8080
</code></pre>
<ol start="3">
<li>查看sentinel控制台<br><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671687135570.png" alt="1671687135570"></li>
</ol>
<h2 id="控制台规则"><a href="#控制台规则" class="headerlink" title="控制台规则"></a>控制台规则</h2><h3 id="BlockException异常统一处理"><a href="#BlockException异常统一处理" class="headerlink" title="BlockException异常统一处理"></a>BlockException异常统一处理</h3><p>实现BlockExceptionHandler即可</p>
<pre><code class="java">@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler &#123;

    Logger log = LoggerFactory.getLogger(this.getClass());

    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception &#123;
        log.info(&quot;BlockExceptionHandler BlockException================&quot;+e.getRule());
        Result r = null;

        if (e instanceof FlowException) &#123;
             r = Result.error(100,&quot;接口限流了&quot;);

             &#125; else if (e instanceof DegradeException) &#123;
             r = Result.error(101,&quot;服务降级了&quot;);

             &#125; else if (e instanceof ParamFlowException) &#123;
              r = Result.error(102,&quot;热点参数限流了&quot;);

             &#125; else if (e instanceof SystemBlockException) &#123;
              r = Result.error(103,&quot;触发系统保护规则了&quot;);

             &#125; else if (e instanceof AuthorityException) &#123;
              r = Result.error(104,&quot;授权规则不通过&quot;);
             &#125;

         //返回json数据
        response.setStatus(500);
        response.setCharacterEncoding(&quot;UTF-8&quot;);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), r);


    &#125;
&#125;
</code></pre>
<p>这样就可以根据不同的Exception的类型进行统一的返回了，需要定制化的返回还是需要使用@SentinelResource注解。</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671707295772.png" alt="1671707295772"></p>
<p>资源的对应关系，需要知晓一下</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671713588184.png" alt="1671713588184"></p>
<p>设置add流控规则触发流控后会执行自己定义的blockHandler，设置自动识别的就会执行BlockExce统一的异常处理。同一个资源都配置了的话会执行统一异常处理。</p>
<h3 id="流控规则（flow-contorl）"><a href="#流控规则（flow-contorl）" class="headerlink" title="流控规则（flow contorl）"></a>流控规则（flow contorl）</h3><p>原理是通过监控应用流量的QPS或者并发线程数等指标，当达到指定的阈值时对流量进行控制，以避免被瞬间流量高峰冲垮，从而保障应用的高可用性。通常在服务提供端进行配置。</p>
<p>适用场景：</p>
<ul>
<li>应对洪峰流量：秒杀，大促，下单，订单回流处理</li>
<li>消息型场景：削峰填谷，冷热启动</li>
<li>付费系统：根据使用流量付费</li>
<li>API GateWay：精准控制API流量</li>
<li>任何应用：探测应用中运行的慢程序块进行限制</li>
</ul>
<h4 id="限流阈值类型"><a href="#限流阈值类型" class="headerlink" title="限流阈值类型"></a>限流阈值类型</h4><ul>
<li>QPS（Query per Sercond）<br>每秒请求数，服务器在一秒的时间内处理了多少个请求</li>
<li>线程数<br>并发线程数控制用于保护业务线程池不被慢调用耗尽。Sentinel并发控制不负责创建和管理线程池，而是简单的统计当前请求上下文的线程数目（正在执行的调用数目），如果超出阈值，新的请求会被立即拒绝，效果类似于信号量隔离。并发数控制通常在调用端进行配置。</li>
</ul>
<p>QPS和线程数流控的区别：</p>
<p>QPS是单位时间内请求的次数不能超过阈值，否则就触发流控规则；线程数是超过阈值的线程数就触发流控规则。</p>
<h4 id="流控模式"><a href="#流控模式" class="headerlink" title="流控模式"></a>流控模式</h4><ul>
<li><p>直接<br>资源调用达到设置的阈值后会被直接被流控抛出异常</p>
</li>
<li><p>关联<br>关联资源触发流控后，资源名中的资源就会触发流控<br>例如下图：add添加资源触发限流，get获取资源也会被限流</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1671766472937.png" alt="1671766472937"></p>
</li>
<li><p>链路<br>资源之间通过调用关系，形成调用关系树。</p>
</li>
</ul>
<p>如下图：/order/add资源和/order/get资源都调用了hello资源就会形成一个以hello为根节点，/order/add资源和/order/get资源为叶子节点的调用关系树。</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672036660937.png" alt="1672036660937"></p>
<p>设置hello资源，入口资源为/order/get时。当hello触发限流，会对入口资源/order/get进行限流，但是同样调用hello资源的/order/add资源不会被限流，可以调用hello资源。</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672036902326.png" alt="1672036902326"></p>
<p><strong>使用链路模式时需要注意：</strong></p>
<ul>
<li><p>需要添加web-context-unify配置为false</p>
<pre><code class="yml">    sentinel:
      transport:
        dashboard: 127.0.0.1:8080
      web-context-unify: false
</code></pre>
</li>
<li><p> 链路模式拦截不到BlockException，需要使用@SentinelResource注解，配合blockHandler处理BlockEXception。</p>
</li>
</ul>
<h4 id="流控效果"><a href="#流控效果" class="headerlink" title="流控效果"></a>流控效果</h4><ul>
<li>快速失败（默认）<br>当限流阈值达到设定的值，后面的请求就会直接失败。</li>
<li>Warm Up（激增流量）<br>预热模式，在预热时长内，面对突然增加的大流量，直接把系统拉高至高水位可能把系统压垮，Warm Up模式就是让通过的流量缓慢的增加，在一定的时间内增加到阈值上限，给冷系统一个预热的时间，避免冷系统被压垮。<br><strong>冷加载因子：</strong>codeFactor默认是3，也就从阈值的1/3开始处理请求，经预热时长逐渐升高到设定的阈值。</li>
<li>排队等待（脉冲流量）<br>让请求匀速的排队通过，而不是直接的拒绝请求。这种效果适合于处理间歇性的突发流量，在某一秒有大量的请求到来，而下几秒则处于空闲状态，我们就可以使用这空闲的时间处理这些短时间内来的大量的请求，而不是一开始就直接拒绝所有的请求。</li>
</ul>
<h3 id="熔断降级"><a href="#熔断降级" class="headerlink" title="熔断降级"></a>熔断降级</h3><p>除了流量控制以外，对调用链路中不稳定的资源进行熔断降级也是保障系统高可用的重要措施之一。我们需要对不稳定的弱依赖服务进行熔断降级，暂时切断不稳定应用，避免局部的不稳定因素导致系统整体的雪崩。熔断降级作为保护自身的手段，通常在客户端（调用端）进行配置。</p>
<h4 id="熔断策略"><a href="#熔断策略" class="headerlink" title="熔断策略"></a>熔断策略</h4><ul>
<li><p>慢调用比例<br>设置允许的慢调用RT（最大的响应时间，也就是请求响应时间大于RT则统计为慢调用），在单位统计时长（控制台内默认是1000ms，高版本的控制台可以设置<strong>统计时长</strong>的值）内请求数目大于设置的最小请求数目，并且慢调用比例大于设置的比例阈值， 则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态 （HALF­_OPEN 半开状态），<strong>半开状态：若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断，若大于设置的慢调用RT则会再次被熔断。</strong><br>下图的策略：统计时长1s内最少请求5次，响应时间有0.5个超过1000ms就会触发熔断，熔断时间长度为10s。熔断后进入（HALF_OPEN）半开状态。</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672058516779.png" alt="1672058516779"></p>
</li>
<li><p>异常比例<br>理解了慢调用比例就明白异常比例，将慢调用比例中的慢调用理解为异常数即可。页面上其他的参数含义不变。<br><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672058953966.png" alt="1672058953966"></p>
</li>
<li><p>异常数<br>异常数和异常比例意思是一样的，只是数量和比例的区别。</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672059223808.png" alt="1672059223808"></p>
</li>
</ul>
<h3 id="热点规则"><a href="#热点规则" class="headerlink" title="热点规则"></a>热点规则</h3><p>热点也就是经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的数据，并对其访问进行限制，我们就可以采用热点规则。<br>热点参数限流会统计传入参数中的热点参数，并根据配置的限流阈值与模式，对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制，仅对包含热点参数的资源调用生效。<br><strong>注意：</strong></p>
<ol>
<li>热点规则需要使用@SentinelResource(“resourceName”)注解，否则不生效 </li>
<li>参数必须是7种基本数据类型才会生效<br><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672147282162.png" alt="1672147282162"></li>
</ol>
<p>新增热点规则：</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672146664707.png" alt="1672146664707"><br>编辑热点规则：添加热点数据信息</p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672147191292.png" alt="1672147191292"></p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672147093822.png" alt="1672147093822"></p>
<h3 id="系统规则"><a href="#系统规则" class="headerlink" title="系统规则"></a>系统规则</h3><p> Sentinel 系统自适应限流从整体维度对应用入口流量进行控制，结合应用的 Load、CPU 使用率、总体平均 RT、入口QPS和并发线程数等几个维度的监控指标，通过自适应的流控策略，让系统的入口流量和系统的负载达到一个平衡，让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。 </p>
<p><img src="https://gitee.com/xiaomaer-sss/picgo/raw/master/images/2023/1672468687739.png" alt="1672468687739"></p>
<ul>
<li>LOAD<br>load自适应，仅针对linux/unix-like机器生效。系统的load1作为启发指标，进行自适应系统保护。当系统load超过设定的启发值，且系统当前的并发线程数超过估算的系统容量时就会触发系统保护（BBR阶段）。系统容量由系统的MaxQPS * MinRt估算得出，设定参考值一般是CPU cores * 2.5。<br>参考理解什么是LOAD：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/gentlemanhai/p/8484839.html">https://www.cnblogs.com/gentlemanhai/p/8484839.html</a></li>
<li>RT<br>平均RT。当单台机器上所有入口流量的平均RT达到阈值就会触发系统保护，单位是毫秒。</li>
<li>线程数<br>并发线程数。当单台机器上所有入口流量的并发线程数达到阈值就会触发系统保护。</li>
<li>入口QPS<br>当单台机器上所有入口流量的QPS达到阈值就会触发系统保护。</li>
<li>CPU使用率<br>当系统CPU使用率超过阈值就会触发系统保护规则。</li>
</ul>
<h2 id="OpenFeign整合Sentinel"><a href="#OpenFeign整合Sentinel" class="headerlink" title="OpenFeign整合Sentinel"></a>OpenFeign整合Sentinel</h2><ul>
<li><p>引入依赖</p>
<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-alibaba-nacos-discovery&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-alibaba-sentinel&lt;/artifactId&gt;
&lt;/dependency&gt;
</code></pre>
</li>
<li><p>开启OpenFeign整合sentinel</p>
<pre><code>feign:
  sentinel:
    # OpenFeign整合sentinel，默认关闭
    enabled: true
</code></pre>
</li>
<li><p>编写OpenFeign接口</p>
<pre><code class="java">@FeignClient(value = &quot;stock-service&quot;,path = &quot;/stock&quot;,fallbackFactory = StockFeignServiceFallbackFactory.class)
public interface StockFeignService &#123;

    @RequestMapping(&quot;/deduct&quot;)
    String deduct();

&#125;
</code></pre>
</li>
<li><p>编写fallbackFactory异常处理类<br>建议使用fallbackFactory，而不建议使用fallback。使用fallbackFactory可以有更灵活的操作。</p>
<pre><code class="java">@Component
public class StockFeignServiceFallbackFactory implements FallbackFactory&lt;StockFeignService&gt;&#123;

    Logger log = LoggerFactory.getLogger(this.getClass());

    public StockFeignService create(Throwable throwable) &#123;

        log.error(&quot;异常原因&#123;&#125;&quot;,throwable.getMessage(),throwable);

        return new StockFeignService() &#123;
            public String deduct() &#123;
                return &quot;OpenFeign调用异常了&quot;;
            &#125;
        &#125;;
    &#125;
&#125;
</code></pre>
<p>当调用stock-service服务的/stock/deduct接口出现异常时，就会执行StockFeignServiceFallbackFactory中deduct 方法中的代码，在这里面就可以进行异常处理，流控处理，降级处理等操作了。GateWay整合sentinel。</p>
</li>
</ul>

      
       <hr><span style="font-style: italic;color: gray;"> 转载请注明来源，欢迎对文章中的引用来源进行考证，欢迎指出任何有错误或不够清晰的表达。可以邮件至 jackma.h@foxmail.com </span>
    </div>
</article>


<p>
    <a  class="dashang" onclick="dashangToggle()">💰</a>
</p>






    




    </div>
    <div class="copyright">
        <p class="footer-entry">
    ©2017 kiwi
</p>
<p class="footer-entry">Built with <a href="https://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/yelog/hexo-theme-3-hexo" target="_blank">3-hexo</a> theme</p>

    </div>
    <div class="full-toc">
        <button class="full" data-title="切换全屏 快捷键 s"><span class="min "></span></button>
<a class="" id="rocket" ></a>

    </div>
</div>

<div class="hide_box" onclick="dashangToggle()"></div>
<div class="shang_box">
    <a class="shang_close"  onclick="dashangToggle()">×</a>
    <div class="shang_tit">
        <p>Help us with donation</p>
    </div>
    <div class="shang_payimg">
        <div class="pay_img">
            <img src="/img/alipay.jpg" class="alipay" title="扫码支持">
            <img src="/img/weixin.jpg" class="weixin" title="扫码支持">
        </div>
    </div>
    <div class="shang_payselect">
        <span><label><input type="radio" name="pay" checked value="alipay">alipay</label></span><span><label><input type="radio" name="pay" value="weixin">weixin</label></span>
    </div>
</div>


</body>
<script src="/js/jquery.pjax.js?v=1.1.0" ></script>

<script src="/js/script.js?v=1.1.0" ></script>
<script>
    var img_resize = 'default';
    function initArticle() {
        /*渲染对应的表格样式*/
        
            $("#post .pjax table").addClass("green_title");
        

        /*渲染打赏样式*/
        
        $("input[name=pay]").on("click", function () {
            if($("input[name=pay]:checked").val()=="weixin"){
                $(".shang_box .shang_payimg .pay_img").addClass("weixin_img");
            } else {
                $(".shang_box .shang_payimg .pay_img").removeClass("weixin_img");
            }
        })
        

        /*高亮代码块行号*/
        

        /*访问数量*/
        
        $.getScript("//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js");
        

        /*代码高亮，行号对齐*/
        $('.pre-numbering').css('line-height',$('.has-numbering').css('line-height'));

        
        
    }

    /*打赏页面隐藏与展示*/
    
    function dashangToggle() {
        $(".shang_box").fadeToggle();
        $(".hide_box").fadeToggle();
    }
    

</script>

<!--加入行号的高亮代码块样式-->

<!--自定义样式设置-->
<style>
    
    
    .nav {
        width: 542px;
    }
    .nav.fullscreen {
        margin-left: -542px;
    }
    .nav-left {
        width: 120px;
    }
    
    
    @media screen and (max-width: 1468px) {
        .nav {
            width: 492px;
        }
        .nav.fullscreen {
            margin-left: -492px;
        }
        .nav-left {
            width: 100px;
        }
    }
    
    
    @media screen and (max-width: 1024px) {
        .nav {
            width: 492px;
            margin-left: -492px
        }
        .nav.fullscreen {
            margin-left: 0;
        }
    }
    
    @media screen and (max-width: 426px) {
        .nav {
            width: 100%;
        }
        .nav-left {
            width: 100%;
        }
    }
    
    
    .nav-right .title-list nav a .post-title, .nav-right .title-list #local-search-result a .post-title {
        color: #383636;
    }
    
    
    .nav-right .title-list nav a .post-date, .nav-right .title-list #local-search-result a .post-date {
        color: #5e5e5f;
    }
    
    
    .nav-right nav a.hover, #local-search-result a.hover{
        background-color: #e2e0e0;
    }
    
    

    /*列表样式*/
    
    #post .pjax article .article-entry>ol, #post .pjax article .article-entry>ul, #post .pjax article>ol, #post .pjax article>ul{
        border: #e2dede solid 1px;
        border-radius: 10px;
        padding: 10px 32px 10px 56px;
    }
    #post .pjax article .article-entry li>ol, #post .pjax article .article-entry li>ul,#post .pjax article li>ol, #post .pjax article li>ul{
        padding-top: 5px;
        padding-bottom: 5px;
    }
    #post .pjax article .article-entry>ol>li, #post .pjax article .article-entry>ul>li,#post .pjax article>ol>li, #post .pjax article>ul>li{
        margin-bottom: auto;
        margin-left: auto;
    }
    #post .pjax article .article-entry li>ol>li, #post .pjax article .article-entry li>ul>li,#post .pjax article li>ol>li, #post .pjax article li>ul>li{
        margin-bottom: auto;
        margin-left: auto;
    }
    

    /* 背景图样式 */
    
    #post {
        background: url([object Object]);
    }
    
    
    #post .index {
        background: url([object Object]);
    }
    


    /*引用块样式*/
    

    /*文章列表背景图*/
    
    .nav-right:before {
        content: ' ';
        display: block;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0.3;
        background: url("https://i.loli.net/2019/07/22/5d3521411f3f169375.png");
        background-repeat: no-repeat;
        background-position: 50% 0;
        -ms-background-size: cover;
        -o-background-size: cover;
        -moz-background-size: cover;
        -webkit-background-size: cover;
        background-size: cover;
    }
    

    
</style>







</html>
